//
//  Playlist.swift
//  hello
//
//  Created by 赵康 on 2025/4/13.
//

import Fluent
import Vapor

final class Playlist: Model, Content, @unchecked Sendable {
  static var schema: String { SchemaEnum.playlists.rawValue }
  
  @ID(key: .id)
  var id: UUID?
  
  @Field(key: FieldKeys.name)
  var name: String
  
  @OptionalField(key: FieldKeys.description)
  var description: String?
  
  @OptionalField(key: FieldKeys.cover)
  var cover: String?
  
  @Parent(key: FieldKeys.user)
  var user: User
  
  @Field(key: FieldKeys.audioIds)
  var audioIds: [UUID]
  
  @Field(key: FieldKeys.audioAddedDates)
  var audioAddedDates: [String: Double] // 存储音频添加日期，格式为 {"audioId字符串": 时间戳}
  
  @Field(key: FieldKeys.type)
  var type: PlaylistType
  
  @Field(key: FieldKeys.sortOrder)
  var sortOrder: Int
  
  @Field(key: FieldKeys.isDeleted)
  var isDeleted: Bool
  
  @Timestamp(key: FieldKeys.createdAt, on: .create)
  var createdAt: Date?
  
  @Timestamp(key: FieldKeys.updatedAt, on: .update)
  var updatedAt: Date?
  
  enum PlaylistType: String, Codable {
    case favorite
    case custom
  }
  
  init() { }
  
  init(
    id: UUID? = nil,
    name: String,
    description: String? = nil,
    cover: String? = nil,
    userID: User.IDValue,
    audioIds: [UUID] = [],
    audioAddedDates: [String: Double] = [:],
    type: PlaylistType = .custom,
    sortOrder: Int = 0,
    isDeleted: Bool = false
  ) {
    self.id = id
    self.name = name
    self.description = description
    self.cover = cover
    self.$user.id = userID
    self.audioIds = audioIds
    self.audioAddedDates = audioAddedDates
    self.type = type
    self.sortOrder = sortOrder
    self.isDeleted = isDeleted
  }
}

// 请求和响应模型
extension Playlist {
  struct Create: Content {
    let name: String
    let description: String?
    let cover: String?
  }
  
  struct Update: Content {
    let name: String?
    let description: String?
    let cover: String?
  }
  
  struct Response: Content {
    let id: UUID
    let name: String
    let description: String?
    let cover: String?
    let audioIds: [UUID]
    let audioAddedDates: [String: Double]
    let type: PlaylistType
    let sortOrder: Int
    let createdAt: Date?
    let updatedAt: Date?
  }
  
  struct AddAudios: Content {
    let audioIds: [UUID]
  }
  
  struct ReorderAudios: Content {
    let fromIndices: [Int]
    let toIndex: Int
  }
}

